package org.aaron.wbclient.utils;

import java.io.IOException;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

public class ImageLoaderUtils {
	private Map<String, SoftReference<Drawable>> cacheImageMaps = new HashMap<String, SoftReference<Drawable>>();

	public Drawable loaderDrawable(final String url, final ImageCallBack imageCallBack) {

		if (cacheImageMaps.containsKey(url)) {
			SoftReference<Drawable> reference = cacheImageMaps.get(url);
			if (reference != null) {
				return reference.get();
			}
		}
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				imageCallBack.imageloader((Drawable) msg.obj);
			}
		};
		new Thread() {
			public void run() {
				Drawable drawable = loaderImageFromUrl(url);
				cacheImageMaps.put(url, new SoftReference<Drawable>(drawable));
				Message message = handler.obtainMessage(0, drawable);
				handler.sendMessage(message);
			};
		}.start();
		return null;
	}

	public Drawable loaderImageFromUrl(String url) {
		try {
			return Drawable.createFromStream(new URL(url+"/120").openStream(), "src");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public interface ImageCallBack {
		public void imageloader(Drawable drawable);
	}

}
